package pers.jason.wppm.security.authentication;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import pers.jason.wppm.security.core.validate.code.support.SimpleResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出成功处理器
 */
public class DefaultLogoutSuccessHandler implements LogoutSuccessHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    private String logoutPage;

    public DefaultLogoutSuccessHandler(String logoutPage) {
        this.logoutPage = logoutPage;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if(StringUtils.isEmpty(logoutPage)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(SimpleResponse.createSuccessResponse("退出登陆成功")));
        } else {
            response.sendRedirect(logoutPage);
        }
    }
}
